package cn.tedu.mall.order.service.impl;

import cn.tedu.mall.order.mappers.OrderMapper;
import cn.tedu.mall.order.service.IOrderAddService;
import cn.tedu.mall.pojo.order.dto.OrderAddCondition;
import cn.tedu.mall.pojo.order.dto.OrderAddDTO;
import cn.tedu.mall.pojo.seckill.dto.SeckillOrderAddDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class OrderAddServiceImpl implements IOrderAddService {
    private static Map<String,IOrderAddService> MAPPER = new HashMap<>();
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    public void addOrder(OrderAddCondition orderAddCondition) {
        //1. 使用sn查询是否已经有订单
        String sn = orderAddCondition.getSn();
        boolean existsOrder = orderMapper.selectExistBySn(sn);
        if (existsOrder){
            log.error("订单已经存在,sn:{},重复下单",sn);
            return;
        }
        // 2. 发送半消息 半消息是不是要发消息?
        // 目的是发送一旦成功,购物车消费者,监听消费删除购物车
        // 通过判断增订单、删库存是否成功，来决定是否发送半消息删除购物车
        // 判断orderAddCondition的类型是本地购物车订单还是秒杀下单订单
        if (orderAddCondition instanceof OrderAddDTO) {
            Message message = MessageBuilder.withPayload(sn).setHeader("tag", "localAdd").build();
            rocketMQTemplate.sendMessageInTransaction(
                    "csmall-tx-cart-delete-topic:localAdd", message, orderAddCondition);
        } else if (orderAddCondition instanceof SeckillOrderAddDTO) {
            Message message = MessageBuilder.withPayload(sn).setHeader("tag", "seckillAdd").build();
            // 秒杀订单不用删除购物车，为啥要发半消息？因为这样才能进入TransactionOrderAddListener，处理之后逻辑
            rocketMQTemplate.sendMessageInTransaction(
                    "csmall-tx-cart-delete-topic:seckillAdd", message, orderAddCondition);
        } else {
            log.error("订单类型不属于当前业务选型范畴，请检查：{}", orderAddCondition.getClass().getName());
        }
    }

    public static void register(String className, IOrderAddService object){
        MAPPER.put(className, object);
    }
}